package com.study.spring;

import com.study.util.Utils;
import org.springframework.core.task.AsyncListenableTaskExecutor;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;

/**
 * @author tc
 * @date 2018/12/27
 */
public class ListenableFutureDemo {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        AsyncListenableTaskExecutor executor = new SimpleAsyncTaskExecutor("ListenableFutureDemo-");

        ListenableFuture<Integer> future = executor.submitListenable(new Callable<Integer>() {

            @Override
            public Integer call() throws Exception {
                return 1;
            }
        });

        future.addCallback(new ListenableFutureCallback<Integer>() {
            @Override
            public void onFailure(Throwable ex) {
                Utils.println(ex);
            }

            @Override
            public void onSuccess(Integer result) {
                Utils.println(result);
            }
        });

        // Future 直到计算结束 （阻塞）
        future.get();

        future = executor.submitListenable(new Callable<Integer>() {

            @Override
            public Integer call() throws Exception {
                return 2;
            }
        });

        future.addCallback(new ListenableFutureCallback<Integer>() {
            @Override
            public void onFailure(Throwable ex) {
                Utils.println(ex);
            }

            @Override
            public void onSuccess(Integer result) {
                Utils.println(result);
            }
        });

        // Future 直到计算结束 （阻塞）
        future.get();
    }

}
